<template>
  <div class="pagerInfo">
    <el-row class="header" type="flex" justify="space-between">
      <span class="header-title">{{ isEdit === 'handler' ? '处理':'编辑' }}公文</span>
    </el-row>
    <el-row :gutter="10" class="content">
      <el-col class="content-left" :xs="24" :sm="24" :md="24" :lg="17" :xl="17">
        <el-tabs v-model="activeName">
          <el-tab-pane name="first">
            <span slot="label">
              <i class="el-icon-date"></i> 基础信息
            </span>
            <report-table ref="report"></report-table>
            <el-row>
            </el-row>
          </el-tab-pane>
        </el-tabs>
         <el-row class="input-box"  v-if="isEdit === 'create'">
          <span class="title">选择流程</span>
          <el-select size="small" v-model="processID" clearable placeholder="请选择">
            <el-option
            v-for="item in processOptions"
            :key="item.ID_"
            :label="item.NAME_"
            :value="item.KEY_">
            </el-option>
        </el-select>
        </el-row>    
         <el-row class="input-box" v-if="isEdit === 'handler'">
          <span class="title">评论</span>
          <el-input type="text" size="small" v-model="comment"></el-input>
        </el-row>    
        <el-row type="flex" class="input-box"> 
          <el-button type="primary" size="small" @click="handPost" v-if="isEdit !== 'handler'">保存</el-button>
          <el-button type="success" size="small" @click="handProcess" :disabled="!processID || !pagerInfo" v-if="isEdit !== 'handler'">流转</el-button>
          <el-button type="primary" size="small" @click="handSaveProcess" v-if="isEdit === 'handler'">保存流转</el-button>
          <el-button type="danger" size="small" @click="handReject" v-if="isEdit === 'handler'">驳回</el-button>
        </el-row>
      </el-col>
      <el-col class="content-right" :xs="24" :sm="24" :md="24" :lg="7" :xl="7">
        <div class="desc">
          <div style="margin-bottom:20px">附件</div>
          <file-check ref="upload" :preview="isEdit !== 'create'"></file-check>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
 import {
    mapGetters
  } from 'vuex'
import { getPaperClassify, getPagerById } from "@/api/document.js";
import { getProcess, startProcess, completeTasks } from "@/api/workflow.js";
import { parseTime, getFileType, fileJoinBaseUrl } from "@/utils/index.js";

import axios from 'axios'
import Cookies from 'js-cookie'
import { Message } from 'element-ui'
export default {
  name: "handlerPager",
  components: {
    ReportTable: () => import("./ReportTable/index.vue"),
    FileCheck: () => import("./FileCheck")
  },
  props: {
      isEdit: {
        type: String,
        default: 'create'
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'id'
      ])
    },
  data() {
    return {
      activeName: "first",
      pagerInfo: null,
      processOptions: [],
      comment: '', // 评论
        processID: '',
        targetID: null,
      }
  },
  created() {
      if (this.isEdit !== 'create') {
        const id = this.$route.params && this.$route.params.id
        this.targetID = this.$route.query && this.$route.query.targetID
        this.fetchData(id)
      }
      this.requestProcess() // 初始化流程列表
    },
  methods: {
    fetchData(id) {
      getPagerById(id).then(res =>{
        const data = res.data
        const tableObj = {
          paper_classfiy: data.paper_classfiy,
          documentType: data.paper_type,
          title: data.title,
          issued_number: data.issued_number,
          postTarget: data.way,
          emergency: data.emergency_level,
          printAmount: data.printAmount
        }
        this.$refs.report.document = tableObj
        
        this.$refs.upload.preiewFileList = fileJoinBaseUrl(data.paperFile)
      })
    },
    requestProcess(){
      getProcess().then(res=>{
        this.processOptions = res.data.data
      })
    },
    findID(data, id){
      data.forEach(e =>{
        if(e.KEY_ === id){
          return e.ID_
        }
      })
    },
    // 提交公文信息
    handPost(){
        const that = this
        const documentObj = this.$refs.report.document
        const fileList = this.$refs.upload.fileList
        this.uploadPress = 0
        const config = {
          headers: {
            'Content-Type': 'multipart/form-data',
            'X-CSRFToken': Cookies.get('csrftoken')
          },
          onUploadProgress: progressEvent => {
            let complete = (progressEvent.loaded / progressEvent.total * 100 | 0) 
            this.uploadPress = Number(complete)
          }
        }
        if(!documentObj.title){
            this.$message.warning('公文标题不能为空')
            return
        }
        if(!documentObj.issued_number){
            this.$message.warning('发文字号不能为空')
            return
        }
        const form = new FormData()
        // 遍历上传参数
        Object.keys(documentObj).forEach(key =>{
            form.append(key ,documentObj[key])
        })
        
        if (fileList.length > 0) {
          fileList.forEach(e =>{
            form.append('file', e.raw)
          })
        }
        axios.post('/api/Work/Papers/',
              form, config).then((res) => {
              if (res) {
                this.$notify({
                    title: '成功',
                    message: '新建公文成功',
                    type: 'success'
                });
                // 保存公文基本信息
                const param = {
                  "bussinesskey":res.data.id,
                  "bussId":res.data.id,
                  "bussName":res.data.title,
                  "bussType":"SP",
                  "targetUnitId":"",
                  // "bussinessKey": res.data.id,
                  "startUserId": this.id
                }
                this.pagerInfo = param
              }
              })
              .catch(function (error) {
                Message({
                  message: '错了哦,创建公文失败',
                  type: 'error',
                  duration: 5 * 1000
                })
              })
    },
    // 处理流转
    handProcess(){
      const ID_ = this.findID(this.processOptions, this.processID)
      const param = Object.assign({ proDefId: ID_ }, this.pagerInfo)
      startProcess(this.processID,param).then(res =>{
        if(res && res.data.success){
          this.$notify({
              title: '成功',
              message: '启动流转成功',
              type: 'success'
          });
        }else{
          this.$notify({
              title: '失败',
              message: '启动流转失败',
              type: 'error'
          });
        }
      })
    },
    // 保存流程
    handSaveProcess(){
      const param = {
        dealReason: this.comment,
        dealType: '0',
        dealUserId: this.name,
        dealUnitId:"0"
      }
      completeTasks(this.targetID, param).then(res =>{
        if(res && res.data === true){
          this.$notify({
              title: '成功',
              message: '保存流转成功',
              type: 'success'
          });
        }else{
          this.$notify({
              title: '失败',
              message: '保存流转失败',
              type: 'error'
          });
        }
      })
    },
    // 驳回
    handReject(){
      const param = {
        dealReason: this.comment,
        dealType:"1",
        rejectNodeId:"S00000"
      }
      completeTasks(this.targetID, param).then(res =>{
        if(res && res.data === true){
          this.$notify({
              title: '成功',
              message: '驳回审批成功',
              type: 'success'
          });
        }else{
          this.$notify({
              title: '失败',
              message: '驳回审批失败',
              type: 'error'
          });
        }
      })
    }
  }
};
</script>
<style lang="scss">
.pagerInfo {
  .header {
    padding: 10px 18px;
    border-bottom: 1px solid #ddd;
    font-size: 18px;
    font-weight: 600;
    line-height: 2;
  }

  .content {
    &-left,
    &-right {
      .desc {
        padding: 10px 20px;
      }
    }
    &-left {
      min-height: 320px;
      .input-box{
        display: flex;
        align-content: center;
        margin: 20px 20px;
        >.el-button{
          margin-right: 10px;
        }
        .title{
                display: inline-block;
                color: #585858;
            font-size: 16px;
            padding: 8px 0;
            min-width: 80px;
        }
    }
      .subTask {
        color: #409eff;
      }
    }
    &-right {
        /* height: calc(100vh - 107px); */
      border-left: 1px solid #ccc;
      .baseinfo {
        padding: 0 20px;
      }
    }
  }
}
</style>
<style>
.el-form-item {
  margin: 0;
}
.el-form-item__label {
  text-align: left;
  font-size: 13px;
  color: #909090;
  font-weight: normal;
}
.el-form-item__content {
  font-size: 13px;
}
.el-tabs {
  margin: 0 20px;
}

.el-tabs__nav-scroll {
  padding: 0 15px;
}
.el-tabs__item {
  height: 43px !important;
}
</style>